package com.tanhua.server.peachblossom.job;


import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.server.api.PeachBlossomApi;
import com.tanhua.dubbo.server.pojo.PeachBlossom;
import com.tanhua.server.peachblossom.pojo.UserInfo;
import com.tanhua.server.peachblossom.service.UserInfoService;
import com.tanhua.server.peachblossom.utils.NoAuthorization;
import org.apache.logging.log4j.spi.LoggerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SoundRegularClearJob {

    @Reference(version = "1.0.0")
    private PeachBlossomApi peachBlossomApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    private static final Logger LOGGER = LoggerFactory.getLogger(SoundRegularClearJob.class);

    @NoAuthorization
    @Scheduled(cron = "0 0/1 * * * *") //每分执行，用于测试
//    @Scheduled(cron = "0 0 3 * * ?") //每天凌晨3点执行，清除逻辑：大于7天不进行更新的，就删除
    public void run() {
        System.out.println("你好，这里是定时任务！");
        long nowTimeMillis = System.currentTimeMillis();

        List<PeachBlossom> peachBlossomList = this.peachBlossomApi.queryPeachList();
        for (PeachBlossom peachBlossom : peachBlossomList) {

            //1.通过mongodb判断 是否有需要清楚的
            Long created = peachBlossom.getCreated();
            if (nowTimeMillis > created) {
                Long day = (nowTimeMillis - created) / (24 * 3600 * 1000);
                if (day >= 7) {
                    //获取 不合格的useerId
                    Long userId = peachBlossom.getUserId();
                    String url = peachBlossom.getSoundUrl();
                    //mongodb中删除userId数据
                    UserInfo userInfo = this.userInfoService.queryUserInfoById(userId);
                    this.peachBlossomApi.removePeachById(userId, userInfo.getSex().getValue());

                    //清除内存中的语音
                    String PEACH_GROUP_KEY = "PEACH_GROUP_" + userId;
                    String PEACH_PATH_KEY = "PEACH_PATH_" + userId;

                    if (this.redisTemplate.hasKey(PEACH_GROUP_KEY) && this.redisTemplate.hasKey(PEACH_PATH_KEY)) {
                        String group = this.redisTemplate.opsForValue().get(PEACH_GROUP_KEY);
                        String path = this.redisTemplate.opsForValue().get(PEACH_PATH_KEY);
                        try {
                            this.storageClient.deleteFile(group, path);
                        } catch (Exception e) {
                            e.printStackTrace();
                            LOGGER.error("音频文件清除失败");
                        }
                    } else {
                        //可能redis过期了
                        Map<String, String> param = getGroupAndPath(url, this.fdfsWebServer.getWebServerUrl());
                        String group = param.get("group");
                        String path = param.get("path");
                        try {
                            this.storageClient.deleteFile(group, path);
                        } catch (Exception e) {
                            e.printStackTrace();
                            LOGGER.error("音频文件清除失败");
                        }
                    }
                }
            }
        }

    }

    private Map<String, String> getGroupAndPath(String url, String webUrl) {
        Map<String, String> param = new HashMap<>();
        String str = url;
        String replace = str.replace(webUrl, "");
        String[] split = replace.split("/");
        String group = split[0];
        String path = "";
        for (int i = 1; i < split.length; i++) {
            if (i > 1) {
                path += "/" + split[i];
            } else {
                path += split[i];
            }
        }
        param.put("group", group);
        param.put("path", path);
        return param;
    }

}
